<template>
  <div class="data-analysis-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>数据分析</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateRangeChange"
          class="date-picker"
        />
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-wrapper">
      <!-- 用户活跃度趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>用户活跃度趋势</span>
            <el-select v-model="userActivityInterval" @change="handleUserActivityIntervalChange">
              <el-option label="日" value="day"></el-option>
              <el-option label="周" value="week"></el-option>
              <el-option label="月" value="month"></el-option>
            </el-select>
          </div>
        </template>
        <div ref="userActivityChart" class="chart" :style="{ height: '300px' }"></div>
      </el-card>

      <!-- 消息量分布 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>消息类型分布</span>
            <el-button type="text" @click="exportMessageTypeData">导出数据</el-button>
          </div>
        </template>
        <div ref="messageTypeChart" class="chart" :style="{ height: '300px' }"></div>
      </el-card>

      <!-- 聊天活跃度排行榜 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>聊天房间活跃度排行</span>
            <el-select v-model="roomRankingCount" @change="handleRoomRankingCountChange">
              <el-option label="Top 5" value="5"></el-option>
              <el-option label="Top 10" value="10"></el-option>
              <el-option label="Top 20" value="20"></el-option>
            </el-select>
          </div>
        </template>
        <div ref="roomRankingChart" class="chart" :style="{ height: '300px' }"></div>
      </el-card>

      <!-- 用户地域分布 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>用户地域分布</span>
          </div>
        </template>
        <div ref="userRegionChart" class="chart" :style="{ height: '300px' }"></div>
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <div class="card-header">
          <span>详细统计数据</span>
        </div>
      </template>
      <el-table :data="detailedData" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120"></el-table-column>
        <el-table-column prop="activeUsers" label="活跃用户数"></el-table-column>
        <el-table-column prop="newUsers" label="新增用户数"></el-table-column>
        <el-table-column prop="totalMessages" label="消息总数"></el-table-column>
        <el-table-column prop="averageSessionDuration" label="平均会话时长(分钟)"></el-table-column>
        <el-table-column prop="peakConcurrentUsers" label="峰值在线人数"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// 图表实例
const userActivityChart = ref(null)
const messageTypeChart = ref(null)
const roomRankingChart = ref(null)
const userRegionChart = ref(null)

// 日期范围
const dateRange = ref([new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()])

// 图表配置选项
const userActivityInterval = ref('day')
const roomRankingCount = ref('10')

// 详细数据
const detailedData = ref([])

// 模拟数据
const generateMockData = () => {
  // 生成用户活跃度趋势数据
  const userActivityData = []
  const now = new Date()
  
  for (let i = 30; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    const formattedDate = `${date.getMonth() + 1}/${date.getDate()}`
    
    userActivityData.push({
      date: formattedDate,
      activeUsers: Math.floor(Math.random() * 500) + 800,
      newUsers: Math.floor(Math.random() * 100) + 50,
      messages: Math.floor(Math.random() * 5000) + 2000
    })
  }
  
  // 生成消息类型分布数据
  const messageTypeData = [
    { name: '文本', value: Math.floor(Math.random() * 3000) + 5000 },
    { name: '图片', value: Math.floor(Math.random() * 1000) + 2000 },
    { name: '语音', value: Math.floor(Math.random() * 500) + 800 },
    { name: '视频', value: Math.floor(Math.random() * 200) + 300 },
    { name: '文件', value: Math.floor(Math.random() * 100) + 200 }
  ]
  
  // 生成房间活跃度排行数据
  const roomRankingData = []
  const roomNames = ['技术交流群', '产品讨论组', '设计分享', '运营中心', '市场推广', '人力资源', '财务部门', '销售团队', '客服支持', '管理层会议']
  
  for (let i = 0; i < parseInt(roomRankingCount.value); i++) {
    roomRankingData.push({
      name: roomNames[i % roomNames.length] + (i >= roomNames.length ? `(${i - roomNames.length + 1})` : ''),
      messages: Math.floor(Math.random() * 10000) + 5000
    })
  }
  
  // 排序房间活跃度数据
  roomRankingData.sort((a, b) => b.messages - a.messages)
  
  // 生成用户地域分布数据
  const userRegionData = [
    { name: '北京', value: Math.floor(Math.random() * 200) + 300 },
    { name: '上海', value: Math.floor(Math.random() * 200) + 280 },
    { name: '广州', value: Math.floor(Math.random() * 150) + 200 },
    { name: '深圳', value: Math.floor(Math.random() * 150) + 180 },
    { name: '杭州', value: Math.floor(Math.random() * 120) + 150 },
    { name: '成都', value: Math.floor(Math.random() * 100) + 120 },
    { name: '武汉', value: Math.floor(Math.random() * 80) + 100 },
    { name: '西安', value: Math.floor(Math.random() * 70) + 80 },
    { name: '南京', value: Math.floor(Math.random() * 60) + 70 },
    { name: '重庆', value: Math.floor(Math.random() * 60) + 60 }
  ]
  
  // 生成详细数据表格
  const tableData = []
  for (let i = 7; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    
    tableData.push({
      date: formattedDate,
      activeUsers: Math.floor(Math.random() * 500) + 800,
      newUsers: Math.floor(Math.random() * 100) + 50,
      totalMessages: Math.floor(Math.random() * 5000) + 2000,
      averageSessionDuration: Math.floor(Math.random() * 30) + 20,
      peakConcurrentUsers: Math.floor(Math.random() * 300) + 500
    })
  }
  
  return {
    userActivityData,
    messageTypeData,
    roomRankingData,
    userRegionData,
    tableData
  }
}

// 初始化用户活跃度趋势图
const initUserActivityChart = () => {
  if (!userActivityChart.value) return
  
  const chart = echarts.init(userActivityChart.value)
  const { userActivityData } = generateMockData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['活跃用户', '新增用户', '消息量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: userActivityData.map(item => item.date)
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '用户数',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '消息量',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '活跃用户',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: userActivityData.map(item => item.activeUsers),
        smooth: true,
        lineStyle: {
          width: 2
        }
      },
      {
        name: '新增用户',
        type: 'line',
        stack: '总量',
        emphasis: {
          focus: 'series'
        },
        data: userActivityData.map(item => item.newUsers),
        smooth: true,
        lineStyle: {
          width: 2
        }
      },
      {
        name: '消息量',
        type: 'line',
        yAxisIndex: 1,
        emphasis: {
          focus: 'series'
        },
        data: userActivityData.map(item => item.messages),
        smooth: true,
        lineStyle: {
          width: 2
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化消息类型分布图
const initMessageTypeChart = () => {
  if (!messageTypeChart.value) return
  
  const chart = echarts.init(messageTypeChart.value)
  const { messageTypeData } = generateMockData()
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '消息类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: messageTypeData
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化房间活跃度排行图
const initRoomRankingChart = () => {
  if (!roomRankingChart.value) return
  
  const chart = echarts.init(roomRankingChart.value)
  const { roomRankingData } = generateMockData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: roomRankingData.map(item => item.name)
    },
    series: [
      {
        name: '消息量',
        type: 'bar',
        data: roomRankingData.map(item => item.messages),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化用户地域分布图
const initUserRegionChart = () => {
  if (!userRegionChart.value) return
  
  const chart = echarts.init(userRegionChart.value)
  const { userRegionData } = generateMockData()
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户数',
        type: 'bar',
        data: userRegionData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ff9a9e' },
            { offset: 1, color: '#fad0c4' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 刷新所有数据
const refreshData = () => {
  ElMessage({ message: '数据刷新中...', type: 'info' })
  
  // 模拟加载延迟
  setTimeout(() => {
    initUserActivityChart()
    initMessageTypeChart()
    initRoomRankingChart()
    initUserRegionChart()
    
    // 更新表格数据
    const { tableData } = generateMockData()
    detailedData.value = tableData
    
    ElMessage({ message: '数据刷新成功', type: 'success' })
  }, 500)
}

// 导出消息类型数据
const exportMessageTypeData = () => {
  ElMessage({ message: '数据导出成功', type: 'success' })
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  refreshData()
}

// 处理用户活跃度时间间隔变化
const handleUserActivityIntervalChange = () => {
  initUserActivityChart()
}

// 处理房间排行数量变化
const handleRoomRankingCountChange = () => {
  initRoomRankingChart()
}

// 页面加载时初始化
onMounted(() => {
  nextTick(() => {
    // 初始化图表
    initUserActivityChart()
    initMessageTypeChart()
    initRoomRankingChart()
    initUserRegionChart()
    
    // 初始化表格数据
    const { tableData } = generateMockData()
    detailedData.value = tableData
  })
})
</script>

<style scoped>
.data-analysis-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.date-picker {
  width: 300px;
}

.charts-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
  flex: 1;
  overflow-y: auto;
}

.chart-card {
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: 600;
  color: #303133;
}

.chart {
  width: 100%;
}

.data-table-card {
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-wrapper {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .date-picker {
    width: 100%;
  }
}
</style>